package com.wanlian.common;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;

public class IntRmb {


    public static float intRmb()  {

        IntRmb intRmb=new IntRmb();
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        String httpUrl = "https://api.coinmarketcap.com/v2/ticker/2399/";
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
            JSONObject jsonstr = new JSONObject(result);
            String o=jsonstr.get("data").toString();
            System.out.println("o:"+o);

            JSONObject jsonstr2= new JSONObject(o);
            String o1=jsonstr2.get("quotes").toString();
            System.out.println("o1:"+o1);

            JSONObject jsonstr3= new JSONObject(o1);
            String o2=jsonstr3.get("USD").toString();
            System.out.println("o2:"+o2);

            JSONObject jsonstr4= new JSONObject(o2);
            float o3=intRmb.rounding(Float.parseFloat(jsonstr4.get("price").toString()));
            System.out.println("String o3:"+o3);
            System.out.println("floag  o3:"+jsonstr4.get("price").toString());
            ExchangeRate exchangeRate=new ExchangeRate();
            exchangeRate.getRequest3();
            float rmb=(float) o3*Float.parseFloat(exchangeRate.getRequest3());
            return  intRmb.rounding(rmb);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static void main(String[] args) {
        IntRmb t=new IntRmb();
        System.out.println(t.intRmb());
    }


    //四舍五入
    public static  float rounding(float num) {
        BigDecimal b = new BigDecimal(num);
        float re_num = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        return re_num;
    }


}
